import axios from "axios";
import { getCookie } from "@/utils/utils";
import { ElMessage } from "element-plus";

// 创建 axios 实例
const service = axios.create({
  baseURL: "http://127.0.0.1:8080/api/public/", // 根据实际情况设置

  timeout: 50000, // 请求超时时间（毫秒）
});

const errResHandle = (error) => {
  const errResponse = error.response.data;
  if (errResponse) {
    ElMessage.error(errResponse.message);
  } else {
    ElMessage.error(error.message);
  }
};

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加Content-Type头
    config.headers["Content-Type"] = "application/json";
    // 从cookie获取token
    const token = getCookie("token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.data) {
      ElMessage.success(response.data.message);
    }
    return response.data;
  },
  (error) => {
    errResHandle()
    return Promise.reject(error);
  }
);

// 封装 get 方法
export function get(url, params = {}, config = {}) {
  return service.get(url, { params, ...config });
}

// 封装 post 方法
export function post(url, data = {}, config = {}) {
  return service.post(url, data, { ...config });
}

export default service;
